﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using DuJianliang.ApplicationPlatform.Common;

namespace DuJianliang.ApplicationPlatform.UserPermission
{
    public partial class UserEdit : System.Web.UI.Page
    {
        UserPermissionBll userPermissionBll = new UserPermissionBll();

        public string ID
        {
            set
            {
                ViewState["ID"] = value;
            }
            get
            {
                return ViewState["ID"] != null ? ViewState["ID"].ToString() : string.Empty;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                UserPermissionBll userPermissionBll = new UserPermissionBll();
                if (!userPermissionBll.HasPermission(CurrentInfo.Instance.CurrentUser.ID, (int)Permission.UserManager))
                {
                    Response.Write("您没有权限使用该功能");
                    Response.End();
                    return;
                }
                this.ID = Request.QueryString["id"];
                InitControlData(this.ID);
            }
        }

        private void InitControlData(string id)
        {
            if (string.IsNullOrWhiteSpace(id)) return;

            string sql = @"SELECT * FROM dbo.t5715_User WHERE UserID = @ID";

            try
            {
                Database database = DatabaseFactory.CreateDatabase();
                DbCommand dbCommand = database.GetSqlStringCommand(sql);
                database.AddInParameter(dbCommand, "@ID", DbType.String, id);

                using (IDataReader reader = database.ExecuteReader(dbCommand))
                {
                    if (reader.Read())
                    {
                        txt1.Text = reader["Username"] != null ? reader["Username"].ToString() : string.Empty;
                        txt1.ReadOnly = true;
                        txt2.Text = reader["Password"] != null ? reader["Password"].ToString() : string.Empty;
                        txt3.Text = reader["TrueName"] != null ? reader["TrueName"].ToString() : string.Empty;
                        txt4.Text = reader["Email"] != null ? reader["Email"].ToString() : string.Empty;

                        hidDeptID.Value = reader["DeptID"] != null ? reader["DeptID"].ToString() : string.Empty;
                        txt5.Text = userPermissionBll.GetDeptFullName(hidDeptID.Value);

                        string isAdmin = reader["IsAdmin"] != null ? reader["IsAdmin"].ToString() : string.Empty;

                        if (isAdmin.ToLower().Equals("true"))
                        {
                            rbtnIsAdminYes.Checked = true;
                        }
                        else
                        {
                            rbtnIsAdminNo.Checked = true;
                        }                        
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void UpdateData()
        {
            string username = txt1.Text.Trim();
            string password = txt2.Text.Trim();
            string truename = txt3.Text.Trim();
            string email = txt4.Text.Trim();
            string deptid = hidDeptID.Value;
            string isAdmin = rbtnIsAdminYes.Checked ? "1" : "0";

            if (string.IsNullOrWhiteSpace(this.ID))
            {
                // 判断用户名是否已存在
                string sql_has = @"SELECT COUNT(UserID) FROM dbo.t5715_User WHERE UserName = @UserName";

                // add
                string sql_insert = @"INSERT INTO dbo.t5715_User
                                               ([UserName]
                                               ,[Password]
                                               ,[TrueName]
                                               ,[Email]
                                               ,[IsAdmin]
                                               ,[DeptID])
                                         VALUES
                                               (@UserName
                                               ,@Password
                                               ,@TrueName
                                               ,@Email
                                               ,@IsAdmin
                                               ,@DeptID)";
                try
                {

                    Database database = DatabaseFactory.CreateDatabase();
                    DbCommand dbCommand = database.GetSqlStringCommand(sql_has);
                    database.AddInParameter(dbCommand, "@UserName", DbType.String, username);
                    object obj = database.ExecuteScalar(dbCommand);
                    if (obj.ToString().Equals("1"))
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('用户名已存在');</script>");
                        throw new ApplicationException("用户名已存在");
                    }

                    dbCommand = database.GetSqlStringCommand(sql_insert);
                    database.AddInParameter(dbCommand, "@UserName", DbType.String, username);
                    database.AddInParameter(dbCommand, "@Password", DbType.String, password);
                    database.AddInParameter(dbCommand, "@TrueName", DbType.String, truename);
                    database.AddInParameter(dbCommand, "@Email", DbType.String, email);
                    database.AddInParameter(dbCommand, "@IsAdmin", DbType.String, isAdmin);
                    database.AddInParameter(dbCommand, "@DeptID", DbType.String, deptid);
                    database.ExecuteNonQuery(dbCommand);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            { 
                // update
                string sql_update = @"UPDATE dbo.t5715_User
                                           SET [Password] = @Password
                                              ,[TrueName] = @TrueName
                                              ,[Email] = @Email
                                              ,[IsAdmin] = @IsAdmin
                                              ,[DeptID] = @DeptID
                                         WHERE UserID = @UserID";
                try
                {

                    Database database = DatabaseFactory.CreateDatabase();
                    DbCommand dbCommand = database.GetSqlStringCommand(sql_update);
                    database.AddInParameter(dbCommand, "@UserID", DbType.String, this.ID);
                    database.AddInParameter(dbCommand, "@Password", DbType.String, password);
                    database.AddInParameter(dbCommand, "@TrueName", DbType.String, truename);
                    database.AddInParameter(dbCommand, "@Email", DbType.String, email);
                    database.AddInParameter(dbCommand, "@IsAdmin", DbType.String, isAdmin);
                    database.AddInParameter(dbCommand, "@DeptID", DbType.String, deptid);
                    database.ExecuteNonQuery(dbCommand);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }           
               
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                UpdateData();
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存成功');</script>"); 
            }
            catch
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('保存失败');</script>"); 
            }            
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("UserList.aspx");
        }
    }
}